package com.kdd.campus.sh.service.impl;

import com.github.pagehelper.PageHelper;
import com.kdd.campus.sh.dao.ShCategoryMapper;
import com.kdd.campus.sh.dao.ShProductMapper;
import com.kdd.campus.sh.dao.ShRecordMapper;
import com.kdd.campus.sh.dao.UserMapper;
import com.kdd.campus.sh.dto.ESProductInfo;
import com.kdd.campus.sh.dto.ProductInfo;
import com.kdd.campus.sh.po.ShCategory;
import com.kdd.campus.sh.po.ShProduct;
import com.kdd.campus.sh.po.ShRecord;
import com.kdd.campus.sh.po.User;
import com.kdd.campus.sh.repository.ESProductRepository;
import com.kdd.campus.sh.service.ShProductService;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/****
 * @Author:shenkunlin
 * @Description:ShProduct业务层接口实现类
 * @Date 2019/6/14 0:16
 *****/
@Service
public class ShProductServiceImpl implements ShProductService {

    @Autowired
    private ShProductMapper productMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ESProductRepository productRepository;

    @Autowired
    private ShRecordMapper recordMapper;

    @Autowired
    private ShCategoryMapper categoryMapper;


    @Override
    public ArrayList<ProductInfo> findByCategory2(Integer cid, int page, int size) {
        ShProduct shProduct = new ShProduct();
        shProduct.setCategoryId(cid);

        // 调用条件查询方法
        return findProductInfoPage(shProduct,page,size);
    }

    // 获取精品商品
    @Override
    public List<ProductInfo> getQualityProducts(int page, int pageSize) {
        ShProduct product = new ShProduct();
        product.setIsNew(1);
        return findProductInfoPage(product, page,pageSize);
    }

    @Override
    public ArrayList<ProductInfo> findByCategory1(Integer cid, int page, int pageSize) {
        // 查询1级分类的所有子分类
        List<ShCategory> subCategory = categoryMapper.select(ShCategory.builder().parentId(cid).build());
        if (subCategory.isEmpty()){return null;}

        // 获取所有子分类的id
        List<Integer> subCategoryIds = subCategory.stream().map(category -> category.getId()).collect(Collectors.toList());

        //分页
        PageHelper.startPage(page,pageSize);
        Example example = new Example(ShProduct.class);
        example.createCriteria()
                .andIn("categoryId",subCategoryIds);

        return  productToProductInfo(productMapper.selectByExample(example));
    }

    @Override
    public List<ProductInfo> getHotProduct(Map<String, String> conditionMap) {
        PageHelper.startPage(1, 30);
        Example example = new Example(ShProduct.class);
        example.setOrderByClause("created desc");
        if (conditionMap.containsKey("order")){
            String order = conditionMap.get("order").equals("asc")?"price asc":"price desc";
            example.setOrderByClause(order);
        }
        example.createCriteria()
                .andEqualTo("isHot",1)
                .andEqualTo("status",1);

        return productToProductInfo(productMapper.selectByExample(example));
    }

    @Override
    public List<ProductInfo> getNewProduct(Map<String, String> conditionMap) {
        String order = conditionMap.get("order");
        if (order != null){
            // 防止前端乱传值
            order = order.equals("desc")?"desc":"asc";
        }
        return productToProductInfo(productMapper.getNewProduct(order));
    }


    @Override
    public List<ESProductInfo> searchByKeyword(Long userId, String keyword, Integer pageNum, Integer pageSize) {
        // 条件构造
        PageRequest pageable = PageRequest.of(pageNum, pageSize);
        NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
        nativeSearchQueryBuilder.withQuery(QueryBuilders.matchQuery("productName",keyword));
        nativeSearchQueryBuilder.withPageable(pageable);

        // 执行查询
        Page<ESProductInfo> searchResult = productRepository.search(nativeSearchQueryBuilder.build());

        /**
         * 搜索历史
         * 1. 先根据关键字和用户id查找用户是否查询过
         * 2. 查询过的话，修改使count+1并修改status=1（可见），否则插入
         */
        ShRecord shRecord = recordMapper.selectOne(ShRecord.builder().keyword(keyword).userId(userId).build());
        if (shRecord != null){
            // 修改历史记录信息
            shRecord.setCount(shRecord.getCount()+1);
            shRecord.setStatus(1);
            shRecord.setModified(new Date());
            recordMapper.updateByPrimaryKeySelective(shRecord);
        }else{
            // 新增搜索历史记录
            ShRecord newRecord = ShRecord.builder()
                    .userId(userId)
                    .keyword(keyword)
                    .created(new Date())
                    .count(1)
                    .modified(new Date()).build();
            recordMapper.insert(newRecord);
        }
        return searchResult.getContent();
    }




    /**
     * ShProduct条件+分页查询
     * @param shProduct 查询条件
     * @param page 页码
     * @param size 页大小
     * @return 分页结果
     */
    @Override
    public ArrayList<ProductInfo> findProductInfoPage(ShProduct shProduct, int page, int size){
        //分页
        PageHelper.startPage(page,size);

        //搜索条件构建
        Example example = createExample(shProduct);

        //分页查询
        List<ShProduct> shProducts = productMapper.selectByExample(example);

//        Page<Object> objects = PageHelper.startPage(page, size).doSelectPage(() -> this.userMapper.selectByExample(example));
//        List<Object> result = objects.getResult();

        ArrayList<ProductInfo> productInfoList = productToProductInfo(shProducts);
        return productInfoList;
    }

    // 将实体类转换成dto
    private ArrayList<ProductInfo> productToProductInfo(List<ShProduct> shProducts) {
        ArrayList<ProductInfo> productInfoList = new ArrayList<>();
        shProducts.forEach(product -> {
            // 查询商品对应的用户
            User user = userMapper.selectByPrimaryKey(product.getUserId());

            ProductInfo productInfo = ProductInfo.builder().build()
                    .setPid(product.getId())
                    .setPImg(product.getCoverUrl())
                    .setPName(product.getName())
                    .setPrice(product.getPrice())
                    .setUImg(user.getHeadPortrait())
                    .setUsername(user.getUsername());
            productInfoList.add(productInfo);
        });
        return productInfoList;
    }

    /**
     * ShProduct分页查询
     * @param page
     * @param size
     * @return
     */
    @Override
    public List<ProductInfo> findProductInfoPage(int page, int size){
        // 调用条件查询方法(条件查询的特殊情况，无条件)
        return findProductInfoPage(null , page ,size);
    }

    /**
     * ShProduct条件查询
     * @param shProduct
     * @return
     */
    @Override
    public List<ShProduct> findList(ShProduct shProduct){
        //构建查询条件
        Example example = createExample(shProduct);
        //根据构建的条件查询数据
        return productMapper.selectByExample(example);
    }


    /**
     * ShProduct构建查询对象
     * @param shProduct
     * @return
     */
    public Example createExample(ShProduct shProduct){
        Example example=new Example(ShProduct.class);
        Example.Criteria criteria = example.createCriteria();
        if(shProduct!=null){
            // 
            if(!StringUtils.isEmpty(shProduct.getId())){
                    criteria.andEqualTo("id",shProduct.getId());
            }
            // 
            if(!StringUtils.isEmpty(shProduct.getCategoryId())){
                    criteria.andEqualTo("categoryId",shProduct.getCategoryId());
            }
            // 
            if(!StringUtils.isEmpty(shProduct.getUserId())){
                    criteria.andEqualTo("userId",shProduct.getUserId());
            }
            // 商品打折后的价格
            if(!StringUtils.isEmpty(shProduct.getPrice())){
                    criteria.andEqualTo("price",shProduct.getPrice());
            }
            // 原价
            if(!StringUtils.isEmpty(shProduct.getOriginalPrice())){
                    criteria.andEqualTo("originalPrice",shProduct.getOriginalPrice());
            }
            // 商品信息描述(不超过500字)
            if(!StringUtils.isEmpty(shProduct.getDescription())){
                    criteria.andEqualTo("description",shProduct.getDescription());
            }
            // 商品浏览数
            if(!StringUtils.isEmpty(shProduct.getBrowseCount())){
                    criteria.andEqualTo("browseCount",shProduct.getBrowseCount());
            }
            // 商品名称
            if(!StringUtils.isEmpty(shProduct.getName())){
                    criteria.andLike("name","%"+shProduct.getName()+"%");
            }
            // 商品数量
            if(!StringUtils.isEmpty(shProduct.getProductNum())){
                    criteria.andEqualTo("productNum",shProduct.getProductNum());
            }
            // 创建时间
            if(!StringUtils.isEmpty(shProduct.getCreated())){
                    criteria.andEqualTo("created",shProduct.getCreated());
            }
            // 修改时间
            if(!StringUtils.isEmpty(shProduct.getModified())){
                    criteria.andEqualTo("modified",shProduct.getModified());
            }
//            // 商品图片
//            if(!StringUtils.isEmpty(shProduct.getProductImg())){
//                    criteria.andEqualTo("productImg",shProduct.getProductImg());
//            }
            // 状态(0:下架 1:正常显示 2:售完)
            if(!StringUtils.isEmpty(shProduct.getStatus())){
                    criteria.andEqualTo("status",shProduct.getStatus());
            }
            // 发布者最后一次来看该商品的时间
            if(!StringUtils.isEmpty(shProduct.getLastComeTime())){
                    criteria.andEqualTo("lastComeTime",shProduct.getLastComeTime());
            }
            // 是否是新品(0:不是新品 1:新品)
            if(!StringUtils.isEmpty(shProduct.getIsNew())){
                    criteria.andEqualTo("isNew",shProduct.getIsNew());
            }
            // 是否实拍(0:不是 1:是)
            if(!StringUtils.isEmpty(shProduct.getIsRealShotting())){
                    criteria.andEqualTo("isRealShotting",shProduct.getIsRealShotting());
            }
            // 是否送货上门(0:不是 1:是)
            if(!StringUtils.isEmpty(shProduct.getIsHomeDelivery())){
                    criteria.andEqualTo("isHomeDelivery",shProduct.getIsHomeDelivery());
            }
        }
        return example;
    }

    /**
     * 删除
     * @param id
     */
    @Override
    public void delete(Long id){
        productMapper.deleteByPrimaryKey(id);
    }

    /**
     * 修改ShProduct
     * @param shProduct
     */
    @Override
    public void update(ShProduct shProduct){
        productMapper.updateByPrimaryKey(shProduct);
    }

    /**
     * 增加ShProduct
     * @param shProduct
     */
    @Override
    public void add(ShProduct shProduct){
        productMapper.insert(shProduct);
    }

    /**
     * 根据ID查询ShProduct
     * @param id
     * @return
     */
    @Override
    public ShProduct findById(Long id){
        return  productMapper.selectByPrimaryKey(id);
    }

    /**
     * 查询ShProduct全部数据
     * @return
     */
    @Override
    public List<ShProduct> findAll() {
        return productMapper.selectAll();
    }


}
